package com.ruoyi.project.yf.service.impl;

import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.RedisKeyConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.yf.domain.YfStock;
import com.ruoyi.project.yf.domain.YfStockNotice;
import com.ruoyi.project.yf.domain.vo.AvgLine;
import com.ruoyi.project.yf.domain.vo.StockAnaly;
import com.ruoyi.project.yf.service.IYfStockMyService;
import com.ruoyi.project.yf.service.IYfStockNoticeService;
import com.ruoyi.project.yf.service.IYfStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ruoyi.project.yf.mapper.YfStockDayLineMapper;
import com.ruoyi.project.yf.domain.YfStockDayLine;
import com.ruoyi.project.yf.service.IYfStockDayLineService;
import org.springframework.web.client.RestTemplate;

/**
 * 股票日均线Service业务层处理
 * 
 * @author 云峰
 * @date 2020-06-15
 */
@Service
public class YfStockDayLineServiceImpl implements IYfStockDayLineService 
{

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private YfStockDayLineMapper yfStockDayLineMapper;

    @Autowired
    private IYfStockMyService yfStockMyService;

    @Autowired
    private IYfStockService stockService;

    @Autowired
    private  RedisCache redisCache;

    @Autowired
    private IYfStockNoticeService yfStockNoticeService;
    @Override
    public void updateLinePrice() {
        //取得所有用户添加的股票信息
        List<YfStock> stocks = stockService.selectYfStockVoByUse();
        for (YfStock stock:stocks) {
            YfStockDayLine dayLine=yfStockDayLineMapper.selectYfStockDayLineByStockId(stock.getId());
            if(dayLine==null){
                dayLine=new YfStockDayLine();
                dayLine.setName(stock.getName());
                dayLine.setStockId(stock.getId());
            }
            if(setDayLineData(stock.getCode(),dayLine)){
                this.updateYfStockDayLine(dayLine);
            }

        }

        yfStockMyService.SendNotice();
    }


    public   void  updatePriceByCodes(List<YfStock> stocks){
        String stockCodes="";
        for (YfStock stock:stocks) {
            stockCodes+=stock.getCode()+",";
        }
        stockCodes=stockCodes.substring(0,stockCodes.length()-1);
        String url="http://hq.sinajs.cn/list="+stockCodes;
        HttpHeaders headers = new HttpHeaders();
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36 Edg/81.0.416.68");
//        headers.add("Host","push2his.eastmoney.com");
//        String data = restTemplate.getForObject(url, String.class,new HttpEntity<String>(headers));
        String data = restTemplate.getForObject(url, String.class,new HttpEntity<String>(headers));
        for (YfStock stock:stocks) {
            // 创建 Pattern 对象
            Pattern patt = Pattern.compile(stock.getCode() +"=\"(.+)\";",Pattern.MULTILINE|Pattern.CASE_INSENSITIVE);
            Matcher matcher = patt.matcher(data);
            if(matcher.find()){
                YfStockDayLine dayLine=yfStockDayLineMapper.selectYfStockDayLineByStockId(stock.getId());
                Boolean isExist=true;
                if(dayLine==null){
                    dayLine=new YfStockDayLine();
                    dayLine.setName(stock.getName());
                    dayLine.setStockId(stock.getId());
                    isExist=false;
                }
                String [] stockArr=matcher.group(1).split(",");
                Float curPrice = Float.parseFloat(stockArr[3]);
                dayLine.setCurPrice(curPrice);

                Float lastClose = Float.parseFloat(stockArr[2]);
                Float highPrice = Float.parseFloat(stockArr[4]);
                Float lowerPrice = Float.parseFloat(stockArr[5]);
                dayLine.setLastClose(lastClose);
                dayLine.setHighPrice(highPrice);
                dayLine.setLowerPrice(lowerPrice);

                dayLine.setPercent((dayLine.getCurPrice()-dayLine.getLastClose())/dayLine.getLastClose()*100);
                //技术分析
                String remark="";

//                if(dayLine.getRed()!=null){
//                    //生命线之上
//                    if(curPrice>=dayLine.getRed()&&dayLine.getRed()>dayLine.getLife()){
//                        remark="红线之上，继续持有！";
//                        if(dayLine.getRed()>dayLine.getGreen()){//红在绿上
//                            remark+="【优】";
//                        }else {
//                            remark+="【良】";
//                        }
//                    }else{
//                        if(dayLine.getCurPrice()<dayLine.getLife()){
//                            remark="生命线之下，建议卖出！";
//                        }else {
//                            remark="生命线之上";
//                        }
//                        //股价在生命线下
//                        if(dayLine.getRed()<dayLine.getGreen()){
//                            remark+="【极差】";
//                            if(stock.getName()=="上证指数"){
//                                remark+="大盘死x中，危险";
//                            }
//                        }else{
//                            remark+="【差】";
//                        }
//                    }
//                }

                //从小到大排列
                try {
                    StockAnaly  finaResult=getScoreAndRemark(dayLine);
                    remark=finaResult.getRemark();
//                    List<AvgLine> lines=getAvgLinesBySort(dayLine);
//                    for (int i = 0; i < lines.size(); i++) {
//                        if(dayLine.getCurPrice()>lines.get(i).getPrice()){
//                            //找到当前价格的支撑位
//                            if(i+1<5){
//                                //找到压力位，才能确定最近支撑位置
//                                if(dayLine.getCurPrice()<lines.get(i+1).getPrice()){
//                                    //remark += "支撑位:"+lines.get(i).getName()+"[" + lines.get(i).getPrice() + "]";
//                                    remark += "支撑位:"+lines.get(i).getName()+"[" + lines.get(i).getPrice() + "_" + getPercent(curPrice, lines.get(i).getPrice()) + "%];";
//                                    remark += "压力位:"+lines.get(i+1).getName()+"[" + lines.get(i+1).getPrice() + "_" + getPercent(curPrice, lines.get(i+1).getPrice()) + "%];";
//
//                                    break;
//                                }
//
//                            }
//
//                        }
//                    }
                }catch (Exception e){
                    System.out.println("计算价格异常了："+dayLine.getName());
                    continue;
                }finally {
                    dayLine.setRemark(remark);
                    if(isExist)
                        this.updateYfStockDayLine(dayLine);
                    else
                        this.insertYfStockDayLine(dayLine);

                }


//                if(dayLine.getUpper()!=null) {
//                    //是否上轨道支撑
//                    if (curPrice >= dayLine.getUpper()) {
//                        remark += "支撑位:上轨道[" + dayLine.getUpper() + "]，压力位:无";
//                    } else if (curPrice >= dayLine.getRed() && curPrice <= dayLine.getUpper()) {
//                        remark += "支撑位:红线[" + dayLine.getRed() + "_" + getPercent(curPrice, dayLine.getRed()) + "%]，压力位:上轨道:" + dayLine.getUpper() + "_" + getPercent(curPrice, dayLine.getUpper()) + "%";
//                    } else if (curPrice >= dayLine.getGreen() && curPrice <= dayLine.getRed()) {
//                        remark += "支撑位:绿线[" + dayLine.getGreen() + "_" + getPercent(curPrice, dayLine.getGreen()) + "%]，压力位:红线:" + dayLine.getRed() + "_" + getPercent(curPrice, dayLine.getRed()) + "%";
//                    } else if (curPrice >= dayLine.getLife() && curPrice <= dayLine.getGreen()) {
//                        remark += "支撑位:生命线[" + dayLine.getLife() + "_" + getPercent(curPrice, dayLine.getLife()) + "%]，压力位:绿线:" + dayLine.getGreen() + "_" + getPercent(curPrice, dayLine.getGreen()) + "%";
//                        ;
//                    } else if (curPrice >= dayLine.getLower() && curPrice <= dayLine.getLife()) {
//                        remark += "支撑位:下轨道[" + dayLine.getLower() + "_" + getPercent(curPrice, dayLine.getLower()) + "%]，压力位:生命线:" + getPercent(curPrice, dayLine.getLife()) + "%";
//                        ;
//                    }
//                }
                //看是否有支撑
//                if(dayLine.getRed()>=dayLine.getGreen()&&dayLine.getGreen()>=dayLine.getLife()){
//                    if(curPrice>=dayLine.getRed()){
//                        remark+="支撑位:红线["+dayLine.getRed()+"]，压力位:上轨道:"+dayLine.getUpper();
//                    }else if(curPrice>=dayLine.getGreen()){
//                        remark+="支撑位:绿线["+dayLine.getGreen()+"]，压力位:红线:"+dayLine.getRed();
//                    }else {
//                        remark+="支撑位:生命线["+dayLine.getLife()+"],压力位:绿线:"+dayLine.getGreen();;
//                    }
//                }



            }
        }
    }

    @Override
    public void updatePrice() {
        //取得所有用户添加的股票信息
        List<YfStock> stocks = stockService.selectYfStockVoByUse();
        updatePriceByCodes(stocks);
    }


    private  List<AvgLine> getAvgLinesBySort(YfStockDayLine DayLine){
        ArrayList<AvgLine>  result=new ArrayList<AvgLine>();
        try {
            result.add(new AvgLine("上轨道",DayLine.getUpper()));
            result.add(new AvgLine("红线",DayLine.getRed()));
            result.add(new AvgLine("绿线",DayLine.getGreen()));
            result.add(new AvgLine("生命线",DayLine.getLife()));
            result.add(new AvgLine("下轨道",DayLine.getLower()));

            //使用Collections集合工具类进行排序
            Collections.sort(result, new Comparator<AvgLine>() {

                @Override
                public int compare(AvgLine o1, AvgLine o2) {
                    //升序排序，降序反写
                    //return  (int) (o1.getPrice()-o2.getPrice());
                    return new Double(o1.getPrice()).compareTo(new Double(o2.getPrice()));
                }

            });
        }catch (Exception ex){

        }

        return  result;
    }

    public  float getPercent(float curPrice,float basePrice){
       float result = (curPrice-basePrice)/basePrice*100;
        DecimalFormat fmt = new DecimalFormat("##0.00");
        String s = fmt.format(result);
        float f1 = Float.parseFloat(s);
        return  f1;
    }


    private  void GetDayLineInfo(String url, YfStockDayLine dayLine) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36 Edg/81.0.416.68");
        headers.add("Host","push2his.eastmoney.com");
//        String data = restTemplate.getForObject(url, String.class,new HttpEntity<String>(headers));
        JSONObject data = restTemplate.getForObject(url, JSONObject.class,new HttpEntity<String>(headers));
        JSONArray klines = data.getJSONObject("data").getJSONArray("klines");
        List<Float> list=new ArrayList();
        for (Integer i=0;i<klines.size();i++){
            String item=klines.getString(i).split(",")[1];
            list.add(Float.parseFloat(item));
        }
        List<Float> listDay8=list;
        dayLine.setRed(getEXPMA(listDay8,8));
        dayLine.setGreen(getEXPMA(listDay8,21));
        dayLine.setLife(getEXPMA(listDay8,144));

        //UPPER1:MA(CLOSE,60)+2*STD(CLOSE,60)
        if(list.size()>=60){
            Float[]  list60 = list.subList(list.size()-60,list.size()).toArray( new Float[60]);
            Float upperPrice=Float.parseFloat(Sum(list60)/60+2*POP_STD_dev(list60)+"");
            dayLine.setUpper(upperPrice);
            Float lowerPrice=Float.parseFloat(Sum(list60)/60-2*POP_STD_dev(list60)+"");
            dayLine.setLower(lowerPrice);
        }

    }

    ///观察上证指数  日线级，和60分钟级别
    //
    public  void  NoticeSZZS(){

        YfStockDayLine  szdayLine=yfStockDayLineMapper.selectYfStockDayLineByStockId(141l);

        YfStockDayLine dayLine=new YfStockDayLine();
        String url="https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.000001&fields1=f1,f3&fields2=f51,f53&lmt=120&klt=60&fqt=1&end=30000101";
        GetDayLineInfo(url,dayLine);
        dayLine.setCurPrice(szdayLine.getCurPrice());
        //先分析60分钟
 //       String result="";
//        int  Score=10;
//        //从小到大排列
//        if(dayLine.getCurPrice()>dayLine.getLife()){
//            result="牛;";
//        }else{
//            result="熊;";
//            Score-=6;
//        }
//
//
//
//        //从小到大排列
//        List<AvgLine> lines=getAvgLinesBySort(dayLine);
//        for (int i = 0; i < lines.size(); i++) {
//            if(dayLine.getCurPrice()>lines.get(i).getPrice()){
//                //找到当前价格的支撑位
//                if(i+1<5){
//                    //找到压力位，才能确定最近支撑位置
//                    AvgLine pressLine=lines.get(i+1);
//                    if(dayLine.getCurPrice()<pressLine.getPrice()){
//                       if(pressLine.getName().equals("上轨道")){
//                           Score-=2;
//                       }else if(pressLine.getName().equals("红线")){
//                           if(dayLine.getRed()<dayLine.getGreen()){
//                               Score-=6;
//                           }else {
//                               Score-=3;
//                           }
//                       }else if(pressLine.getName().equals("绿线")){
//                           if(dayLine.getCurPrice()>dayLine.getRed()){
//                               Score-=4;
//                           }
//                       }
//
//                       else if(pressLine.getName().equals("生命线")){
//                           Score-=7;
//                       }
//
//                        result += "支撑位:"+lines.get(i).getName()+";";
//                        result += "压力位:"+lines.get(i+1).getName()+";";
//
//                        break;
//                    }
//                }
//
//            }
//        }
//
//
//        if(dayLine.getRed()<=dayLine.getGreen()&&dayLine.getCurPrice()<=dayLine.getRed()){
//            result+="危险:死X中,准备割肉吧;";
//            if(dayLine.getCurPrice()<dayLine.getLife()){
//                result+="生命线都破了，清仓吧！";
//            }
//        }else if(dayLine.getRed()>dayLine.getGreen()&&dayLine.getCurPrice()>dayLine.getRed()){
//            result+="正常:金X中;";
//        }
//
//        result="得分/仓位控制:"+Score+" "+result;
//
//        //分析日线
//        dayLine=new YfStockDayLine();
//        dayLine.setCurPrice(szdayLine.getCurPrice());
//        url="https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.000001&fields1=f1,f3&fields2=f51,f53&lmt=58&klt=101&fqt=1&end=30000101";
//        GetDayLineInfo(url,dayLine);
//        if(dayLine.getRed()<=dayLine.getGreen()){
//            result="危险:大盘日线死X中,清仓吧，不然让你感受一下什么叫绝望";
//            if(dayLine.getCurPrice()<dayLine.getLife()){
//                result+="【日k】生命线都破了，清仓吧！";
//            }
//        }else{
//            if(dayLine.getCurPrice()<=dayLine.getRed()){
//                result+="【日k】当前价格破了红线，减少仓位";
//            }
//        }

        StockAnaly  finaResult=getScoreAndRemark(dayLine);
        Boolean isScoreChange=false;
        String scoreKey="SZZS_SCORE";
        if(redisCache.redisTemplate.hasKey(scoreKey)){
            int NowScore=redisCache.getCacheObject("SZZS_SCORE");
            if(NowScore!=finaResult.getScore()){
                //记录起来
                YfStockNotice yfStockNotice=new YfStockNotice();
                yfStockNotice.setName("上证指数分数变化");
                yfStockNotice.setNoticeType("1");
                yfStockNotice.setRemark(finaResult.getRemark());
                yfStockNotice.setToUid(1);
                yfStockNotice.setCreateBy("admin");
                yfStockNoticeService.insertYfStockNotice(yfStockNotice);
            }
        }


        redisCache.setCacheObject("SZZS_SCORE",finaResult.getScore());
        redisCache.setCacheObject("SZZS",finaResult.getRemark());

        //如果分数发生变化，就记录起来


    }


    private StockAnaly getScoreAndRemark(YfStockDayLine  dayLine){

        String result="";
        int  Score=10;
        List<AvgLine> lines=getAvgLinesBySort(dayLine);
        for (int i = 0; i < lines.size(); i++) {
            if(dayLine.getCurPrice()>lines.get(i).getPrice()){
                //找到当前价格的支撑位
                if(i+1<5){
                    //找到压力位，才能确定最近支撑位置
                    AvgLine pressLine=lines.get(i+1);
                    if(dayLine.getCurPrice()<pressLine.getPrice()){
                        if(pressLine.getName().equals("上轨道")){
                            Score-=2;
                        }else if(pressLine.getName().equals("红线")){
                            if(dayLine.getRed()<dayLine.getGreen()){
                                Score-=6;
                            }else {
                                Score-=3;
                            }
                        }else if(pressLine.getName().equals("绿线")){
                            if(dayLine.getCurPrice()>dayLine.getRed()){
                                Score-=4;
                            }
                        }

                        else if(pressLine.getName().equals("生命线")){
                            Score-=7;
                        }

                        result += "支撑:"+lines.get(i).getName()+"[" + lines.get(i).getPrice() + "_" + getPercent(dayLine.getCurPrice(), lines.get(i).getPrice()) + "%]";
                        result += "压力:"+lines.get(i+1).getName()+"[" + lines.get(i+1).getPrice() + "_" + getPercent(dayLine.getCurPrice(), lines.get(i+1).getPrice()) + "%]";

                        break;
                    }
                }

            }
        }


        if(dayLine.getRed()<=dayLine.getGreen()&&dayLine.getCurPrice()<=dayLine.getRed()){
            result+="危险:死X中,准备割肉吧;";
            if(dayLine.getCurPrice()<dayLine.getLife()){
                result+="生命线都破了，清仓吧！";
            }
        }else if(dayLine.getRed()>dayLine.getGreen()&&dayLine.getCurPrice()>dayLine.getRed()){
            result+="正常:金X中;";
        }

        StockAnaly  finaResult=new StockAnaly(Score,"得分："+Score+" "+result);
        return finaResult;
    }

    public  boolean setDayLineData(String code, YfStockDayLine dayLine){
        boolean result=false;

        //https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.601066&fields1=f1,f3&fields2=f51,f53&lmt=58&klt=101&fqt=1&end=30000101
        //# 另外获取data的网址股票代码 沪市前加0， 深市前加1
        String secid=(code.contains("sh")?1:0)+"."+code.substring(2);
        //lmt=120&klt=60 60分钟
        String url="https://push2his.eastmoney.com/api/qt/stock/kline/get?secid="+secid+"&fields1=f1,f3&fields2=f51,f53&lmt=120&klt=60&fqt=1&end=30000101";

        //String url="https://push2his.eastmoney.com/api/qt/stock/kline/get?secid="+secid+"&fields1=f1,f3&fields2=f51,f53&lmt=400&klt=101&fqt=1&end=30000101";
        HttpHeaders headers = new HttpHeaders();
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36 Edg/81.0.416.68");
        headers.add("Host","push2his.eastmoney.com");
//        String data = restTemplate.getForObject(url, String.class,new HttpEntity<String>(headers));
        JSONObject data = restTemplate.getForObject(url, JSONObject.class,new HttpEntity<String>(headers));
        JSONArray klines = data.getJSONObject("data").getJSONArray("klines");
        List<Float> list=new ArrayList();
        for (Integer i=0;i<klines.size();i++){
            String item=klines.getString(i).split(",")[1];
            list.add(Float.parseFloat(item));
        }


        List<Float> listDay8=list;
        dayLine.setRed(getEXPMA(listDay8,8));
        dayLine.setGreen(getEXPMA(listDay8,21));
        dayLine.setLife(getEXPMA(listDay8,144));

        //UPPER1:MA(CLOSE,60)+2*STD(CLOSE,60)
        if(list.size()>=60){
            Float[]  list60 = list.subList(list.size()-60,list.size()).toArray( new Float[60]);
            Float upperPrice=Float.parseFloat(Sum(list60)/60+2*POP_STD_dev(list60)+"");
            dayLine.setUpper(upperPrice);
            Float lowerPrice=Float.parseFloat(Sum(list60)/60-2*POP_STD_dev(list60)+"");
            dayLine.setLower(lowerPrice);
        }

        result=true;
        return  result;
    }


    // population variance 总体方差
    double POP_Variance(Float[] data) {
        double variance = 0;
        for (int i = 0; i < data.length; i++) {
            variance = variance + (Math.pow((data[i] - Mean(data)), 2));
        }
        variance = variance / data.length;
        return variance;
    }

    // population standard deviation 总体标准差
    double POP_STD_dev(Float[] data) {
        double std_dev;
        std_dev = Math.sqrt(POP_Variance(data));
        return std_dev;
    }


    double Mean(Float[] data) {
        double mean = 0;
        mean = Sum(data) / data.length;
        return mean;
    }

    double Sum(Float[] data) {
        double sum = 0;
        for (int i = 0; i < data.length; i++)
            sum = sum + data[i];
        return sum;
    }

    /**
     * Calculate EMA,
     *
     * @param list
     *            :Price list to calculate，the first at head, the last at tail.
     * @return
     */
    public  final Float getEXPMA(final List<Float> list, final int number) {
        // 开始计算EMA值，
        //当天EMA=昨天的EMA+加权因子*（当天的收盘价-昨天的EMA）=  加权因子*当天的收盘价+（1-加权因子）*昨天的EMA加权因子=2/(N+1);
//        股票上市第一天：当天EMA1 = 当天收盘价1
//        第二天：EMA2 = 2/27*当天收盘价2 +25/27*EMA1
//        第三天：EMA3 = 2/27*当天收盘价3 +25/27*EMA2
        //ema的计算公式是,当日eam等于当制日的收盘价百*百分比+前一日的ema值*(1-百分比)
        //当日指数平均值=平滑系数*（当日指数值-昨日指数平均值）+昨日指数平均值；平滑系数=2/（周期单位+1）
        Double k = 2.0 / (number + 1.0);// 计算出序数
        Float ema = list.get(0);// 第一天ema等于当天收盘价
        for (int i = 1; i < list.size(); i++) {
            //ema = list.get(i) * k + ema * (1 - k);
            //ema=k * (list.get(i)-ema)+ema;
            //ema=(list.get(i)+ema*(number-1))/number;

            //vec[i] = (2 * X[i] + (N - 1) * vec[i - 1]) / (N + 1);
            ema=(2*list.get(i)+(number-1)*ema)/(number+1);
        }
        return ema;
    }

    /**
     * 查询股票日均线
     *
     * @param id 股票日均线ID
     * @return 股票日均线
     */
    @Override
    public YfStockDayLine selectYfStockDayLineById(Long id)
    {
        return yfStockDayLineMapper.selectYfStockDayLineById(id);
    }

    /**
     * 查询股票日均线列表
     *
     * @param yfStockDayLine 股票日均线
     * @return 股票日均线
     */
    @Override
    public List<YfStockDayLine> selectYfStockDayLineList(YfStockDayLine yfStockDayLine)
    {
        return yfStockDayLineMapper.selectYfStockDayLineList(yfStockDayLine);
    }

    /**
     * 新增股票日均线
     *
     * @param yfStockDayLine 股票日均线
     * @return 结果
     */
    @Override
    public int insertYfStockDayLine(YfStockDayLine yfStockDayLine)
    {
        yfStockDayLine.setCreateTime(DateUtils.getNowDate());
        return yfStockDayLineMapper.insertYfStockDayLine(yfStockDayLine);
    }

    /**
     * 修改股票日均线
     *
     * @param yfStockDayLine 股票日均线
     * @return 结果
     */
    @Override
    public int updateYfStockDayLine(YfStockDayLine yfStockDayLine)
    {
        yfStockDayLine.setUpdateTime(DateUtils.getNowDate());
        return yfStockDayLineMapper.updateYfStockDayLine(yfStockDayLine);
    }

    /**
     * 批量删除股票日均线
     *
     * @param ids 需要删除的股票日均线ID
     * @return 结果
     */
    @Override
    public int deleteYfStockDayLineByIds(Long[] ids)
    {
        return yfStockDayLineMapper.deleteYfStockDayLineByIds(ids);
    }

    /**
     * 删除股票日均线信息
     *
     * @param id 股票日均线ID
     * @return 结果
     */
    @Override
    public int deleteYfStockDayLineById(Long id)
    {
        return yfStockDayLineMapper.deleteYfStockDayLineById(id);
    }

    @Override
    public YfStockDayLine selectYfStockDayLineByStockId(Long stockid) {
        return  yfStockDayLineMapper.selectYfStockDayLineByStockId(stockid);
    }



    @Override
    public  String getStockOpenStatus(){
        String result=redisCache.getCacheObject(RedisKeyConstants.OPEN_STATUS);
        if(result==null||result.equals("")){
            String url="https://stock.xueqiu.com/v5/stock/quote.json?symbol=SZ000651&extend=detail";

            HttpHeaders headers = new HttpHeaders();
            headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3756.400 QQBrowser/10.5.4039.400");
            headers.add("Host","stock.xueqiu.com");
            ResponseEntity<String> response = restTemplate.getForEntity("https://xueqiu.com/",  String.class,new HttpEntity<String>(headers));       //地址替换为自己的
            List<String> cookies=response.getHeaders().get("Set-Cookie");

            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add(headers.COOKIE,"xq_a_token=48575b79f8efa6d34166cc7bdc5abb09fd83ce63; xqat=48575b79f8efa6d34166cc7bdc5abb09fd83ce63; xq_r_token=7dcc6339975b01fbc2c14240ce55a3a20bdb7873; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTU4OTY4MjczMCwiY3RtIjoxNTg4OTMxNzMyNzg5LCJjaWQiOiJkOWQwbjRBWnVwIn0.AVsBnYEwG1DrfKaM5cpgp_usCmcSUSHDGlU5JKBIW5K4_2Y6m0Xf5yQ5pog6llR67IgXUVl-VBqDXgdBKXuqar-WdC4_eZ6eM33yWwK48rzdEplrJK3yXKiZXuhSaoTiqnBnzDKdS5LOOcromJWU8j-L5kZbeH68Bo3QCFut9Hj8ZlS10oq38_FM0MDF3Yph17Ge6HHFT4adCIpYSz1aBRWKQNbhBs2OhfVzrmkOh3w4GSSmG3uidciGeZZm_QTtmj6iMqjdS2FQxfb-rVpx548nh1nC-JFeE_Aq1RsGPk_mKiROwoO0AtkJQBBBhMjCGsy0ujgaL9xDO7-PPLwdwA; u=911588931788114; s=bx11o5070e; Hm_lvt_1db88642e346389874251b5a1eded6e3=1588500779,1588508278,1588931790,1588995965; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1588995965");
            requestHeaders.put("Cookie", cookies);

            HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
            JSONObject data =  restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class).getBody();
            String stockStatus=data.getJSONObject("data").getJSONObject("market").getString("status");
            if(!stockStatus.equals("")){
                redisCache.setCacheObject(RedisKeyConstants.OPEN_STATUS,stockStatus,30, TimeUnit.MINUTES);
            }
            result=redisCache.getCacheObject(RedisKeyConstants.OPEN_STATUS);
        }

//        System.out.println(data.getJSONObject("data").getJSONObject("market").getString("status"));
        return result;
    }
}
